/**
 * 前端音频剪切
 */

let recorder;
const chunks = [];
const ctx = new AudioContext();
const aud = document.createElement('audio');
const option = {
    url: null,
    start: 0,
    end: 0,
    callback: null
};

function exportAudio() {
    const blob = new Blob(chunks, { type: 'audio/x-mpeg-3' });
    aud.src = URL.createObjectURL(blob);
    if (option.callback) option.callback(aud.src, blob);
}

function getData() {
    const request = new XMLHttpRequest();
    request.open('GET', option.url, true);
    request.responseType = 'arraybuffer';
    request.onload = decodeAudio;
    request.send();
}

function decodeAudio() {
    const audioData = this.response;
    ctx.decodeAudioData(audioData, startRecording);
}

function startRecording(buffer) {
    const source = ctx.createBufferSource();
    source.buffer = buffer;
    const dest = ctx.createMediaStreamDestination();
    source.connect(dest);

    recorder = new MediaRecorder(dest.stream);
    recorder.ondataavailable = saveChunks;
    recorder.onstop = exportAudio;
    source.start(option.start);
    recorder.start();
    console.log('clipping...');
    setTimeout(() => {
        recorder.stop();
    }, option.end);
}

function saveChunks(evt) {
    if (evt.data.size > 0) {
        chunks.push(evt.data);
    }
}

const clipAudio = (url, timeRange = [0, 2], callback) => {
    option.url = url;
    option.start = timeRange[0] * 1000;
    option.end = timeRange[1] * 1000;
    option.callback = callback;
    getData();
};

export { clipAudio };
